<template>
  <div class="app-container">
    <!-- 侧边栏 -->
    <div class="sidebar">
      <div class="sidebar-header">
        <h2 class="sidebar-title">在线教育平台</h2>
        <el-button icon="el-icon-menu" class="toggle-btn" @click="toggleSidebar"></el-button>
      </div>
      <el-menu
          :default-active="activeMenu"
          class="el-menu-vertical-demo"
          background-color="#0b1b33"
          text-color="#fff"
          active-text-color="#409EFF"
          :collapse="isSidebarCollapse"
          router
      >
        <!-- 修改图标使用为大写开头的组件 -->
        <el-menu-item index="/home">
          <el-icon><Menu /></el-icon>
          <span>课程管理</span>
        </el-menu-item>
        <el-menu-item index="/kgfl">
          <el-icon><Folder /></el-icon>
          <span>课程分类管理</span>
        </el-menu-item>
        <el-menu-item index="/stu">
          <el-icon><user /></el-icon>
          <span>学生管理</span>
        </el-menu-item>
        <el-menu-item index="/teacher">
          <el-icon><user /></el-icon>
          <span>教师管理</span>
        </el-menu-item>
        <el-menu-item index="/per">
          <el-icon><user /></el-icon>
          <span>个人中心</span>
        </el-menu-item>
      </el-menu>
    </div>

    <!-- 主内容区 -->
    <div class="main-content" :class="{ 'sidebar-collapse': isSidebarCollapse }">
      <!-- 面包屑 -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item>课程管理</el-breadcrumb-item>
      </el-breadcrumb>

      <!-- 页面标题与操作 -->
      <div class="page-header">
        <h1 class="page-title">课程列表</h1>
        <!-- 取消注释以显示添加课程按钮 -->
      </div>

      <!-- 搜索筛选区 -->
      <el-card class="search-card">
        <el-form :inline="true" :model="searchForm" class="search-form">
          <el-form-item label="搜索">
            <el-input v-model="searchForm.keyword" placeholder="请输入课程名称/讲师搜索" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><search /></el-icon>搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><refresh /></el-icon>重置
            </el-button>
            <el-button type="primary" @click="handleAddCourse">
              <el-icon><Plus /></el-icon>添加课程
            </el-button>
          </el-form-item>

        </el-form>
      </el-card>

      <!-- 修改课程列表为卡片展示 -->
      <el-card class="course-list-card">
        <div class="course-card-container">
          <el-card
            v-for="course in courseList"
            :key="course.id"
            class="course-card"
            shadow="hover"
          >
            <h3>{{ course.title }}</h3>
            <p>{{ course.description }}</p>
            <p>讲师: {{ course.teacherRealName }}</p>
            <p>分类: {{ course.categoryName }}</p>
            <p>状态: {{ course.status }}</p>
            <div class="course-card-actions">
              <el-button type="primary" size="small" @click="handleEditCourse(course)">
                <el-icon><edit /></el-icon>编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDeleteCourse(course)">
                <el-icon><delete /></el-icon>删除
              </el-button>
            </div>
          </el-card>
        </div>
      </el-card>

      <!-- 添加/编辑课程对话框 -->
      <el-dialog v-model="dialogVisible" title="课程信息" width="60%">
        <el-form :model="formData" ref="formRef" label-width="120px">
          <el-form-item label="课程名称" prop="title">
            <el-input v-model="formData.title" placeholder="请输入课程名称" />
          </el-form-item>
          <el-form-item label="课程分类" prop="category_id">
            <el-select v-model="formData.category_id" placeholder="请选择分类">
              <el-option
                v-for="category in courseCategories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="授课讲师" prop="teacher_id">
            <el-select v-model="formData.teacher_id" placeholder="请选择讲师">
              <el-option
                v-for="teacher in teachers"
                :key="teacher.id"
                :label="teacher.real_name"
                :value="teacher.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="课程状态" prop="status">
            <el-radio-group v-model="formData.status">
              <el-radio label="已发布">已发布</el-radio>
              <el-radio label="未发布">未发布</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="课程描述" prop="description">
            <el-input v-model="formData.description" type="textarea" placeholder="请输入课程描述" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveCourse">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import {
  Plus,
  Search,
  Edit,
  Delete,
  Refresh,
  Menu,
  Folder,
  User
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from "@/utils/request.js";

// 侧边栏相关状态
const isSidebarCollapse = ref(false)
const activeMenu = ref('course-management')
const toggleSidebar = () => {
  isSidebarCollapse.value = !isSidebarCollapse.value
}

// 新增：课程分类数组
const courseCategories = ref([])
// 新增：老师数组
const teachers = ref([])

// 课程管理相关状态
const courseList = ref([]) // 课程列表数据
const total = ref(0) // 总记录数
const searchForm = reactive({
  keyword: '' // 搜索关键词
})
const dialogVisible = ref(false) // 对话框是否显示
const formData = reactive({
  coId: null,
  Tid: '',
  title: '',
  description: '',
  category: '',
  teacher_id: null,
  category_id: null,
  created_at: null,
  status: '未发布'
})

// 表单引用
const formRef = ref(null)

// 获取课程列表数据
const fetchCourseList = async () => {
  try {
    const response = await request('/course/findAll');

    console.log('接口返回:', response.data)

    if (Array.isArray(response.data)) {
      courseList.value = response.data
      console.log('课程列表数据:', courseList.value)
      total.value = courseList.value.length
    } else {
      courseList.value = []
      total.value = 0
      console.warn('接口返回非数组:', response.data)
    }
  } catch (error) {
    console.error('获取课程列表失败:', error)
    ElMessage.error('加载失败，请检查网络或后端服务')
  }
}

// 新增：获取课程分类列表
const fetchCourseCategories = async () => {
  try {
    const response = await request.get('/courseCategories/list');
    if (Array.isArray(response.data)) {
      courseCategories.value = response.data;
    }
  } catch (error) {
    console.error('获取课程分类列表失败:', error);
    ElMessage.error('获取课程分类列表失败，请检查网络或后端服务');
  }
}

// 新增：获取老师列表
const fetchTeachers = async () => {
  try {
    const response = await request('/teachers/list');
    if (Array.isArray(response.data)) {
      teachers.value = response.data;
    }
  } catch (error) {
    console.error('获取老师列表失败:', error);
    ElMessage.error('获取老师列表失败，请检查网络或后端服务');
  }
}

onMounted(() => {
  fetchCourseList()
  // 新增：调用获取课程分类和老师列表的方法
  fetchCourseCategories()
  fetchTeachers()
})

// 搜索课程
const handleSearch = () => {
  fetchCourseList()
}

// 重置搜索条件
const resetSearch = () => {
  searchForm.keyword = ''
  fetchCourseList()
}

// 添加课程
// 确保 handleAddCourse 方法存在，如果不存在则添加
const handleAddCourse = () => {
  // 重置表单数据
  Object.assign(formData, {
    coId: null,
    Tid: '',
    title: '',
    description: '',
    category: '',
    teacher_id: null,
    category_id: null,
    created_at: null,
    status: '未发布'
  });
  dialogVisible.value = true;
};

// 编辑课程
const handleEditCourse = (row) => {
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 修改保存课程（添加/编辑）方法
const saveCourse = async () => {
  try {
    await formRef.value.validate()

    // 显示加载状态
    const loading = ElMessage({ 
      message: '保存中...', 
      type: 'info', 
      duration: 0, 
      showClose: true 
    })

    if (formData.coId) {
      // 编辑操作
      await request.post('/course/', formData)
      ElMessage.success('更新成功')
      // 找到编辑项并更新
      const index = courseList.value.findIndex(item => item.coId === formData.coId)
      if (index !== -1) {
        courseList.value[index] = { ...formData }
      }
    } else {
      // 新增操作
      const response = await request.post('/course/add', formData)
      ElMessage.success('创建成功')
      // 将新添加的课程放到列表最前面
      courseList.value.unshift({ ...formData, coId: response.data.coId })
      total.value++
    }

    dialogVisible.value = false
    loading.close()
  } catch (error) {
    console.error('保存课程失败', error)
    ElMessage.error('保存课程失败，请稍后重试')
  }
}

// 修改删除课程方法
const handleDeleteCourse = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除课程「${row.title}」吗？`,
      '提示',
      { 
        confirmButtonText: '确定', 
        cancelButtonText: '取消', 
        type: 'warning' 
      }
    )

    // 直接从本地列表中移除
    const index = courseList.value.findIndex(item => item.coId === row.coId)
    if (index !== -1) {
      courseList.value.splice(index, 1)
      total.value--
      ElMessage.success('删除成功')
    }
  } catch (error) {
    console.error('删除课程失败', error)
    if (error !== 'cancel') {
      ElMessage.error('删除课程失败，请稍后重试')
    }
  }
}
</script>

<style scoped>
.app-container {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

/* 侧边栏样式 */
.sidebar {
  width: 220px;
  background-color: #0b1b33;
  color: #fff;
  transition: width 0.3s ease-in-out;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 15px 20px;
  border-bottom: 1px solid #1f334b;
}

.sidebar-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.toggle-btn {
  background: transparent;
  border: none;
  color: #fff;
  cursor: pointer;
  font-size: 20px;
}

.el-menu-vertical-demo {
  border-right: none;
}

/* 主内容区样式 */
.main-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  transition: margin-left 0.3s ease-in-out;
}

.sidebar-collapse .main-content {
  margin-left: 64px; /* 侧边栏折叠后，主内容区调整左边距 */
}

/* 面包屑样式 */
.breadcrumb {
  margin-bottom: 10px;
}

/* 页面头部样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

/* 搜索卡片样式 */
.search-card {
  margin-bottom: 20px;
}

.search-card {
  display: flex;
  justify-content: flex-start; /* 让内容靠左侧排列 */
}
.search-form {
  margin-left: 0; /* 移除可能存在的左侧外边距 */
}

/* 课程列表卡片样式 */
.course-list-card {
  margin-bottom: 20px;
}

/* 分页样式 */
.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 对话框样式（可根据需要调整） */
.dialog-footer {
  text-align: right;
}

.course-card-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 20px;
}
.course-card {
  cursor: pointer;
  transition: transform 0.2s;
}
.course-card:hover {
  transform: translateY(-5px);
}
.course-card-actions {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
}
</style>
